package com.yexx.starter.optms.logger.contexts;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: 自定义全局上下文
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2022/06/26-20:31
 */
public class GlobalContextHolder {

    /**
     * only support Map<String, String>
     */
    private final static ThreadLocal<Map<String, String>> CONTEXTS = new TransmittableThreadLocal<>();

    public static void setContext(String key, String value) {
        Map<String, String> map = CONTEXTS.get();
        if (map == null) {
            map = new HashMap<>(1 << 1);
        }
        map.put(key, value);
        CONTEXTS.set(map);
    }

    public static String getContext(String key) {
        Map<String, String> map = CONTEXTS.get();
        if (map == null) {
            return null;
        }
        return map.get(key);
    }

    /**
     * must remove when you finish you task
     */
    public static void clear() {
        CONTEXTS.remove();
    }

}
